package com.example.myproject.zebra.demo1;

import javax.print.*;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;

public class ZplPrinterRobot2 {

    public static void main(String[] args) {
        PrintService[] services = PrintServiceLookup.lookupPrintServices(null,null);
        System.out.println(Arrays.toString(services));
        String printName = "RealZDesignerZT411";
        PrintService printService =getPrintServiceByName(printName,services);

        StringBuilder sb = new StringBuilder();
        sb.append("^XA");
       // sb.append("^SEE:GB18030.DAT^FS");
//        sb.append("^CWT,E:SIMSUN.TTF^FS\n");
//        sb.append("^CI26");
//        sb.append( "^FO100,100^AT,24,24^CI28^FD中文打印测试ABCCCC码333^FS");

        sb.append("^SEE:GB18030.DAT^FS");
        sb.append("^CWJ,E:SIMSUN.TTF^FS\n");//打印机指定1和j都可以
        sb.append("^CI28");
        sb.append("^FO100,100^AJ,40,40^CI28^FD中文打印测试ABCCCC码333^FS");


       // sb.append("^WD*:*.TTF*");//列出所有支持的宋体

//        sb.append("^CW0,E:ARI000.FNT");//打印arial
//        sb.append("^CI28");
//        sb.append("^FO100,500^A0N,60,,E:ARI000.FNT^FR^FDPO:^FS");
//        sb.append("^FO340,500^A0N,60,,E:ARI000.FNT^FR^FD%CustomerPO我的%^FS");
        sb.append("^XZ");
        print(sb.toString(),printService);

    }

    static  PrintService getPrintServiceByName(String printerURI,    PrintService[] services){
        if (services != null && services.length > 0) {
            for (PrintService service : services) {
                if (service.getName().contains(printerURI)) {
                    return  service;

                }
            }
        }
        return  null;
    }

    /**
     * 打印
     * @param zpl 完整的ZPL
     */
    public static  void print(String zpl,PrintService printService){
        if(printService==null){
            System.out.println("打印出错：没有找到打印机");
            return;
        }
        System.out.print("printzpl:"+zpl);
        DocPrintJob job = printService.createPrintJob();
        byte[] by=str2bytes(zpl);//要转为utf-8
        DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
        Doc doc = new SimpleDoc(by, flavor, null);
        try {
            job.print(doc, null);
            System.out.println("已打印");

        } catch (PrintException e) {
            e.printStackTrace();

        }

    }

    /**
     * 字符串转byte[]
     * @param s
     * @return
     */
    private static  byte[] str2bytes(String s) {
        if (null == s || "".equals(s)) {
            return null;
        }
        byte[] abytes = null;
        try {
            abytes = s.getBytes("utf-8");
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
        return abytes;
    }

}
